package com.example.wordcardjavaproject.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.wordcardjavaproject.bean.entity.Word;
import com.example.wordcardjavaproject.bean.form.QueryWord;
import com.example.wordcardjavaproject.bean.form.ResultWord;
import com.example.wordcardjavaproject.mapper.WordMapper;
import com.example.wordcardjavaproject.service.WordService;
import com.example.wordcardjavaproject.utils.SecurityUserIdUtils;
import com.example.wordcardjavaproject.utils.SnowFlake;
import javax.annotation.Resource;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class WordImpl extends ServiceImpl<WordMapper, Word> implements WordService {
    @Resource
    WordMapper wordMapper;

    @Override
    public ResultWord selectWordList(QueryWord queryWord) {
        // 从token中获取用户id，而不是从请求体中获取。
        Long userId = SecurityUserIdUtils.getUserId();
        queryWord.setUserId(userId);
        Page<Word> page = new Page<>(queryWord.getCurrentPage(), queryWord.getPageSize());
        QueryWrapper<Word> wordQueryWrapper = new QueryWrapper<>();
        wordQueryWrapper.eq("user_id", queryWord.getUserId());
        Page<Word> selectPage = wordMapper.selectPage(page, wordQueryWrapper);
        ResultWord resultWord = new ResultWord();
        resultWord.setTotal(selectPage.getTotal());
        resultWord.setList(selectPage.getRecords());
        return resultWord;
    }

    @Override
    public void updateWord(Word word) {
        wordMapper.updateById(word);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addWordByFile(MultipartFile file, Long userId) throws Exception {
        // 读取文件
        InputStream inputStream = null;
        try{
            inputStream = file.getInputStream();
        }catch (IOException e){
            throw new Exception("文件读取失败") ;
        }
        // 创建excel实例
        Workbook wb = null;
        // 判断格式是.xlsx还是.xls
        if (Objects.requireNonNull(file.getOriginalFilename()).matches("^.+\\.(?i)(xlsx)$")) {
            try {
                wb = new XSSFWorkbook(inputStream);
            }catch (IOException e) {
                throw new Exception("读取excel（xlsx）失败!");
            }

        } else {
            try {
                wb = new HSSFWorkbook(inputStream);
            }catch (IOException e) {
                throw new Exception("读取excel（xls）失败!") ;
            }
        }
        // 获取excel第一个表格
        Sheet sheet = wb.getSheetAt(0);
        if (sheet == null) {
            throw  new Exception("该文件没有数据!");
        }
        // 获取列数
        int column = sheet.getRow(0).getPhysicalNumberOfCells();
        // 获取行数
        int rows = sheet.getLastRowNum();

        List<Word> wordList = new ArrayList<>();

        // 遍历Excel
        for (int i = 1; i <= rows;i++) {
            Row row = sheet.getRow(i);
            if (row == null) {
                continue;
            }
            // 遍历列数
            if (Objects.equals(row.getCell(0).getStringCellValue(), "") &&
                    Objects.equals(row.getCell(1).getStringCellValue(), "") &&
                    Objects.equals(row.getCell(1).getStringCellValue(), "")) {
                continue;
            }
            Word word = new Word();
            word.setWord(row.getCell(0).getStringCellValue());
            word.setKana(row.getCell(1).getStringCellValue());
            word.setChinese(row.getCell(2).getStringCellValue());
            word.setUserId(userId);
            word.setId(SnowFlake.nextId());
            word.setCheckCount(0L);
            word.setRightCount(0L);
            wordList.add(word);
        }
        if (!wordList.isEmpty()) {
            wordMapper.addWordList(wordList);
        }
    }

    @Override
    public void addWordByWeb(Word word) {
        word.setId(SnowFlake.nextId());
        word.setCheckCount(0L);
        word.setRightCount(0L);
        List<Word> list = new ArrayList<>();
        word.setUserId(SecurityUserIdUtils.getUserId());
        list.add(word);
        wordMapper.addWordList(list);
    }

    @Override
    public void deleteWord(Word word) {
        wordMapper.deletWord(word);
    }
}
